<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/15
 * Time: 10:52
 */

namespace app\index\controller;
use app\common\controller\PayBase;
use app\index\model\ChongzhiList;
use think\Db;
use think\Exception;

class Payjyzf extends PayBase{
    protected $userId;
    protected $key;
    protected $pay_url;
    protected $back_url;
    protected $href_url;
    public function __construct() {
        parent::__construct();
        $this->userId = '27197';
        $this->key = '1842968131200c7a464b519e490b4de8';
        $this->pay_url = 'http://pay.095pay.com/api/order/pay';
        $this->back_url = 'http://www.my67.cc/index/Payjyzf/callBack';
        $this->href_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payjyzf/hrefUrl';
    }
    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();
        if($pay_type=='null' || $pay_type=='') return packJson('',$pay_type.'请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>14,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
        $remark = $pay_method['type_name'].'-'.$pay_method['name'];

        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
//                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }

        //计算优惠金额
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->find();
        $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
        $zsje = $amount * $user_class['czzsbl'] / 100;
        $zsbs = $user_class['czzsbl'];
        if($amount >= $cz_set['xscz_je']) {
            $msje = $amount * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }
        //充值方案赠送
        $method_money = 0.00;
        if( floatval( $pay_method['money'] ) > 0 ){
            if( 0==intval( $pay_method['method'] ) ){
                //金额
                $method_money = $pay_method['money'];
            }else{
                //比例
                $method_money = floatval($amount) * floatval($pay_method['money']) / 100;
            }
        }
        $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));

        //生成订单号
        $order_sn = 'JYF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //组装数据
        if( 1==$from ) $this->href_url.="Third";

        $data = array();
        $data['p1_mchtid'] = '27197';
        $data['p2_paytype'] = $pay_type;
        $data['p3_paymoney'] = $amount;
        $data['p4_orderno'] = $order_sn;
        $data['p5_callbackurl'] = $this->back_url;
        $data['p6_notifyurl'] = $this->href_url;
        $data['p7_version'] = 'v2.8';
        $data['p8_signtype'] = '1';
        $data['p9_attach'] = $username;
        $data['p10_appname'] = '';
        $data['p11_isshow'] = '0';
        $data['p12_orderip'] = get_ip();

        if( 'FASTPAY'==$pay_type ){
            $data['p13_memberid'] = $user_info['id'];
        }
        $data['sign'] = self::Sign($data,$this->key);
        $respon = self::curlPost($data, $this->pay_url, 2, 60);
        if( $respon && isset($respon['rspCode']) ){
            if( 1==intval($respon['rspCode']) ){
                $u = Db::name('username')->where('username',$username)->value('je');
                $model = new ChongzhiList();

                if($model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'金阳线上上支付','系统自动',get_ip(),0,$pay_type,$zsje,$zsbs,$msje,$msbs,$user_info['us_class'],'',0,$method_money,$u)){
                    $url = $respon['data']['r6_qrcode'];
                    return packJson( $url ,'',200);
                }else{
                    return packJson('',"订单生产错误",500);
                }
            }else{
                $respon['rspMsg'] = isset($respon['rspMsg']) ? $respon['rspMsg'] : $respon['info'];
                return packJson('',$respon['rspMsg'],500);
            }
        }else{
            return packJson('',"接口调用失败",500);
        }
    }
    public function callBack(){

        $partner = input('partner','');
        $ordernumber = input('ordernumber','');
        $orderstatus = input('orderstatus',0);
        $paymoney = input('paymoney',0);
        $sysnumber = input('sysnumber','');
        $attach = input('attach','');
        $sign = input('sign','');
        $ctime = time();
        $sign_str = 'partner='.$partner.'&ordernumber='.$ordernumber.'&orderstatus='.$orderstatus.'&paymoney='.$paymoney.$this->key;
        if (md5($sign_str) == $sign && 1==intval($orderstatus)) {
            //更新用户金额、打码量等相关信息
            $order_info = Db::name('chongzhi_list')->where('ddbh',$ordernumber)->find();
            if(sprintf("%.2f",$order_info['je']) != sprintf("%.2f",$paymoney)) return 'error';
            $user_info = Db::name('username')->where('username',$attach)->find();
            $dml_set = Db::name('xt_dmsz')->where('id',1)->find();
            $xtcz = Db::name('xt_chongzhi')->where('id',1)->find();
            if($xtcz['dmopen'] == 1) {
                $dmls = ($order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je']+ $order_info['method_money']) * $dml_set['xscz_dmbs'];
            }else{
                $dmls = $order_info['je'] * $dml_set['xscz_dmbs'];
            }
            //充值后账户总金额
            $czhje = $order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je'] + $user_info['je']+ $order_info['method_money'];
            //充值总金额
            $czzje = $order_info['je'] + $user_info['czzje'];
            //用户当前打码量
            $dml = $user_info['dml'] + $dmls;
            Db::startTrans();
            try {
                $zt = model('ChongzhiList')->where(['ddbh'=>$ordernumber])->value('zt');
                if( 1==intval($zt) ){
                    throw new Exception("该订单已经成功通知");
                }
                if( !model('ChongzhiList')->updateRechargeInfo($ordernumber,$sysnumber,1,$czhje,$ctime) ){
                    throw new Exception("更新订单信息错误");
                }
                if( !model('Username')->upUserXsczInfo($czhje,$dml,$czzje,$attach) ){
                    throw new Exception("更新用户金额错误");
                }
                Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');
                $fav_money = $order_info['hy_msje']+$order_info['hy_zsje']+ $order_info['method_money'];
                //满送金额，等级赠送金额，充值方案赠送金额
                $extcj = array(
                    'username'=>$user_info['username'],
                    'user_class'=>$user_info['us_class'],
                    'fstime'=>time(),
                    'czadmin' => '系统赠送',
                );
                $cjhje = floatval($order_info['je']) + floatval($user_info['je']) + floatval($order_info['hy_msje']);
                if( floatval($order_info['hy_msje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值满送金额';
                    $extcj['cjje'] = $order_info['hy_msje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['hy_zsje']);
                if( floatval($order_info['hy_zsje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
                    $extcj['cjje'] = $order_info['hy_zsje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['method_money']);
                if( floatval($order_info['method_money']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
                    $extcj['cjje'] = $order_info['method_money'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }

                $data = array('username' =>$attach,'test'=>"您账户充值金额：{$order_info['je']}，赠送金额：{$fav_money}。已充值到账，请注意查收！",'xx_time'=>$ctime,'ifdq'=>0);
                Db::name('xiaoxi')->data($data)->insert();
                Db::commit();
                return 'ok';
            } catch (\Exception $e) {
                Db::rollback();
                return 'error';
            }
        }
        return 'error';
    }
    public function hrefUrl(){
        file_put_contents('jyzf_href.txt', var_export(input(), true) . PHP_EOL, FILE_APPEND);
        $partner = input('partner','');
        $ordernumber = input('ordernumber','');
        $orderstatus = input('orderstatus',0);
        $paymoney = input('paymoney',0);
        $sign = input('sign','');
        $sign_str = 'partner='.$partner.'&ordernumber='.$ordernumber.'&orderstatus='.$orderstatus.'&paymoney='.$paymoney.$this->key;
        if (md5($sign_str) == $sign && 1==intval($orderstatus)) {
            $this->buildHtml("充值成功，{$paymoney} 元已到账");
        }else{
            $this->buildHtml("充值失败");
        }
    }
    public function hrefUrlThird(){
        file_put_contents('jyzf_three.txt', var_export(input(), true) . PHP_EOL, FILE_APPEND);
        $partner = input('partner','');
        $ordernumber = input('ordernumber','');
        $orderstatus = input('orderstatus',0);
        $paymoney = input('paymoney',0);
        $sign = input('sign','');
        $sign_str = 'partner='.$partner.'&ordernumber='.$ordernumber.'&orderstatus='.$orderstatus.'&paymoney='.$paymoney.$this->key;
        if (md5($sign_str) == $sign && 1==intval($orderstatus)) {
            $this->buildHtml("充值成功，{$paymoney} 元已到账",1);
        }else{
            $this->buildHtml("充值失败",1);
        }
    }
    private static function Sign($param, $key) {
        $string = '';
        foreach($param as $k => $value) {
            $string .= $k . '=' . $value . '&';
        }
        $string = rtrim($string, '&');
        return md5($string . $key);
    }
    private static function xmlToArray($xml){
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }
    /**
     * 发送curl-post请求
     * @author Ben
     * @date 2017-10-27
     * @param $aPostData
     * @param $respondType 1 xml 2 json
     * @param $timeout
     * @return array
     */
    private static function curlPost($aPostData, $sUrl, $respondType = 1, $timeout = 5) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $sUrl);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($aPostData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11');// 添加浏览器内核信息，解决403问题 add by ben 2017/10/25

        $response = curl_exec($ch);

        if (1 === $respondType) {
            $res = self::xmlToArray($response);
        } elseif (2 === $respondType) {
            // echo $response;echo '<br>';
            $res = json_decode($response, true);
            // 如果没有decode成功，也许是因为三方用的是GB2312
            if (is_null($res)) {
                $res = json_decode(iconv('GB2312', 'UTF-8', $response), true);
            }
        } else {
            $res = $response;
        }
        curl_close($ch);

        return $res;
    }

    /**
     * 发送curl-get请求
     * @author Ben
     * @date 2017-07-31
     * @param $aData
     * @param $sUrl
     * @param $respondType 1 xml 2 json
     * @param $timeout
     * @return array
     */
    private static function curlGet($aData, $sUrl, $respondType = 1, $timeout = 5) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $sUrl . '?' . http_build_query($aData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
        curl_setopt($ch, CURLOPT_USERAGENT,
            'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11');// 添加浏览器内核信息，解决403问题 add by ben 2017/10/25
        $response = curl_exec($ch);
        if (1 === $respondType) {
            $res = self::xmlToArray($response);
        } elseif (2 === $respondType) {
            $res = json_decode($response, true);
            // 如果没有decode成功，也许是因为三方用的是GB2312
            if (is_null($res)) {
                $res = json_decode(iconv('GB2312', 'UTF-8', $response), true);
            }
        } else {
            $res = $response;
        }
        curl_close($ch);

        return $res;
    }
}